import logging
from datetime import datetime, timedelta, UTC
import jwt
from flask import Request, json

__key = 'wocaonimade'
__algorithm = 'HS256'


def createToken(d: dict):
    d = json.dumps(d)
    return jwt.encode(json.loads(d), __key, __algorithm)


def setKey(k: str):
    global __key
    __key = k


def authToken(token: str):
    if type(token) != str:
        return False
    try:
        info = jwt.decode(token, __key, __algorithm)
        exceedTime = datetime.strptime(info.get('exceedTime'), "%a, %d %b %Y %H:%M:%S %Z")
        exceedTime = exceedTime.replace(tzinfo=UTC)
        # 验证过期时间
        if exceedTime.timestamp() > datetime.now(UTC).timestamp():
            return info
        return False
    except Exception as e:
        logging.error(e.args)
        return False


def authToken2(req: Request):
    token = req.headers.get("Authorization")
    if token is None:
        return None
    info: dict = authToken(token)
    if info is None:
        return None
    return info


def getUserId(req: Request):
    return req.environ.get("UID")
